//
//  WYXWeatherData.m
//  ObserverPattern
//
//  Created by ying on 2016/12/14.
//  Copyright © 2016年 ying. All rights reserved.
//

#import "WYXWeatherData.h"
#import "YXWWeatherData.h"
#import "WYXObserver.h"
#import "WYXHeaders.h"

@interface WYXWeatherData ()<YXWWeatherDataDelegate>
// 用来存放观察者
@property (nonatomic, strong) NSMutableArray <id<WYXObserver>>*observersArr;

@end

@implementation WYXWeatherData

static WYXWeatherData *weatherData;
+ (instancetype)sharedWeatherData{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        weatherData = [[WYXWeatherData alloc] init];
        weatherData.observersArr = [NSMutableArray array];
         // 设置代理
        [YXWWeatherData sharedWeatherDataSDK].delegate = weatherData;
    });
    return weatherData;
}

#pragma mark ****** WYXSubjec ******

// 添加观察者
- (void)registerObserver:(id<WYXObserver>)obj{
    [self.observersArr addObject:obj];
}

// 移除观察者
- (void)removeObserver:(id<WYXObserver>)obj{
    for (id<WYXObserver>oberver in self.observersArr) {
        if ([oberver isEqual:obj]) {
            [self.observersArr removeObject:obj];
        }
    }
    
}

// 通知观察者有更新
- (void)notifyObervers:(NSDictionary *)data{
    for (id<WYXObserver>oberver in self.observersArr) {
        [oberver update:data];
    }
    
}

#pragma mark ****** delegate ******

- (void)updateTemperature:(float)temperature humidity:(float)humidity andPressure:(float)pressure{
    NSDictionary *data = @{
                           TEMP : @(temperature),
                           HUMI : @(humidity),
                           PRES : @(pressure)
                           };
    [self notifyObervers:data];
}

@end
